<?php

namespace Beike\Admin\Services;


use Illuminate\Support\Facades\DB;

class CategoryImport
{
    /**
     * Import categories from a CSV file
     *
     * @param string $filePath Path to the CSV file
     * @return array Result of the import process
     */
    public static function importCategories(string $filePath): array
    {
        try {
            // Check if file exists and is readable
            if (!file_exists($filePath) || !is_readable($filePath)) {
                return [
                    'success' => 0,
                    'errors' => ["File not found or not readable: $filePath"],
                    'skipped' => 0,
                ];
            }

            // Initialize results and track processed categories
            $result = ['success' => 0, 'errors' => [], 'skipped' => 0];
            $parentIds = []; // Store category names to IDs mapping

            // Read CSV file
            $file = fopen($filePath, 'r');
            $header = fgetcsv($file); // Read header row

            // Begin database transaction
            DB::beginTransaction();

            $lineNumber = 2; // Start from line 2 (after header)
            while (($row = fgetcsv($file)) !== false) {
                try {
                    if (count($row) !== 3) {
                        $result['skipped']++;
                        $result['errors'][] = "Invalid column count at line $lineNumber";
                        $lineNumber++;
                        continue;
                    }

                    $parentCate = trim($row[0]);
                    $cateName = trim($row[1]);
                    $level = (int) $row[2];

                    // Validate input
                    if (empty($cateName) || !in_array($level, [1, 2])) {
                        $result['skipped']++;
                        $result['errors'][] = "Invalid data at line $lineNumber: Empty name or invalid level";
                        $lineNumber++;
                        continue;
                    }

                    // Check for duplicate category name
                    if (isset($parentIds[$cateName])) {
                        $result['skipped']++;
                        $result['errors'][] = "Duplicate category name '$cateName' at line $lineNumber";
                        $lineNumber++;
                        continue;
                    }

                    // Insert into categories table
                    $categoryId = DB::table('categories')->insertGetId([
                        'parent_id' => 0, // Will update later for level 2
                        'position' => 0,
                        'active' => 1,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);

                    // Insert into category_descriptions table (English only)
                    DB::table('category_descriptions')->insert([
                        'category_id' => $categoryId,
                        'locale' => 'en',
                        'name' => $cateName,
                        'content' => '', // Default empty description
                        'meta_title' => $cateName,
                        'meta_description' => '',
                        'meta_keywords' => '',
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);

                    // Store category ID
                    $parentIds[$cateName] = $categoryId;

                    // Handle parent-child relationship
                    if ($level === 2 && !empty($parentCate)) {
                        if (isset($parentIds[$parentCate])) {
                            // Update parent_id in categories table
                            DB::table('categories')
                                ->where('id', $categoryId)
                                ->update(['parent_id' => $parentIds[$parentCate]]);

                            // Insert into category_paths for level 1 parent
                            DB::table('category_paths')->insert([
                                [
                                    'category_id' => $categoryId,
                                    'path_id' => $parentIds[$parentCate],
                                    'level' => 0,
                                    'created_at' => now(),
                                    'updated_at' => now(),
                                ],
                                [
                                    'category_id' => $categoryId,
                                    'path_id' => $categoryId,
                                    'level' => 1,
                                    'created_at' => now(),
                                    'updated_at' => now(),
                                ]
                            ]);
                        } else {
                            $result['errors'][] = "Parent category '$parentCate' not found for '$cateName' at line $lineNumber";
                            $lineNumber++;
                            continue;
                        }
                    } else {
                        // Level 1 category, only insert self path
                        DB::table('category_paths')->insert([
                            'category_id' => $categoryId,
                            'path_id' => $categoryId,
                            'level' => 0,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }

                    $result['success']++;
                } catch (\Exception $e) {
                    $result['errors'][] = "Error processing '$cateName' at line $lineNumber: " . $e->getMessage();
                    $lineNumber++;
                    continue;
                }
                $lineNumber++;
            }

            fclose($file);

            // Commit transaction
            DB::commit();
            return $result;

        } catch (\Exception $e) {
            // Rollback on error
            DB::rollBack();
            return [
                'success' => 0,
                'errors' => ["Failed to process CSV: " . $e->getMessage()],
                'skipped' => 0,
            ];
        }
    }
}